/**
 * Created by zyy on 15/7/7.
 * zhangyuyu@superjia.com
 * blog:{
 *     user_id:'', 用户ID
 *     title: '', 文章标题
 *     tag: '', []
 *     description: '', 文章描述
 *     content: '', 文章内容
 *     markdown: '', 原文内容
 *     createTime:'', 创建时间
 * }
 */


var router = require('koa-router')({
    prefix: '/blog'
});
var wrap = require('co-monk')
var parse = require('co-body')

var filter = require('../common/filter')
var utils = require('../common/utils')
var render = require('../common/render')

var db = require('../db')

var blogDao = wrap(db.get('blog'))
var tagDao = wrap(db.get('tag'))
var userDao = wrap(db.get('user'))

// 博客
router.get('/', function * (next) {
    this.body = yield render('blog', this.locals);
}).get('/detail/:id', function * (next) {
    this.body = yield render('blog', this.locals);
}).get('/tag/:id', function * (next) {
    this.body = yield render('blog', this.locals);
})

router.get('/list', function * (next) {
	var tag = this.query.tag;
	var query = {};
	if (tag) query.tag = tag;

	var list = yield blogDao.find(query);

	for (var i =0; i < list.length; i++){
		var userid = list[i].user_id;
		var user = yield userDao.find({_id: userid});
		list[i].user = user[0];
	}

    utils.success(this, list);
})

router.get('/tags', function * (next) {
    var list = yield tagDao.find({});
    utils.success(this, list);
})

router.post('/addtag', function * (next) {
    var body = yield parse(this)
    var type = body.type;
    var tag = yield tagDao.findOne({name: body.tag});

    if (!tag) {
        tag = {
            name: body.tag,
            createTime: Date.now()
        }

        tag = yield tagDao.insert(tag);
    } else {
        if (type == 'rem') {
            yield tagDao.remove(tag);
        };
    }

    utils.success(this, tag);
})


router.get('/details', function * (next) {
    var id = this.query.id;
	var item = yield blogDao.findOne({_id: id});
    item.user = yield userDao.findOne({_id: item.user_id});
    utils.success(this, item);
})

router.post('/add', filter.login, function * (next) {
	var body = yield parse(this)
	var user = this.locals._user;
    var tag = body.tag;

    var newBlog = {
      user_id: user._id,
      title: body.title, 
      tag: JSON.parse(tag), 
      description: body.description,
      content: body.content,
      markdown: body.markdown,
      createTime: Date.now()
	}

	yield blogDao.insert(newBlog);
    utils.success(this, newBlog)
})

module.exports = router